package com.kun.service;

import cn.hutool.core.bean.BeanUtil;
import com.kun.common.Constants;
import com.kun.common.Result;
import com.kun.controller.dto.UpdateUserDto;
import com.kun.controller.dto.UserDto;
import com.kun.entity.Menu;
import com.kun.entity.Role;
import com.kun.entity.RoleMenu;
import com.kun.entity.User;
import com.kun.exception.MyServiceException;
import com.kun.mapper.MenuMapper;
import com.kun.mapper.RoleMapper;
import com.kun.mapper.RoleMenuMapper;
import com.kun.mapper.UserMapper;
import com.kun.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;


    @Override
    public List<User> selectAllUsers() {
        return userMapper.selectAllUsers();
    }

    @Override
    public Integer saveUser(User user) {
        if (user.getId()!=null){
            return userMapper.updateUser(user);
        }else{
            return userMapper.addUser(user);
        }

    }

    @Override
    public Integer deleteUserById(Integer id) {
        return userMapper.deleteUserById(id);
    }

    @Override
    public List<User> queryUsersByCondition(Map map) {
        int pageIndex = (Integer) map.get("pageIndex");
        int pageSize = (Integer) map.get("pageSize");
        pageIndex=(pageIndex-1)*pageSize;
        map.replace("pageIndex",pageIndex);

        return userMapper.queryByLimit(map);
    }

    @Override
    public List<User> calCountByConditions(Map old_map) {
        Map<String, Object> map=old_map;
        return userMapper.calCountByConditions(map);
    }

    @Override
    public Result login(UserDto userDto) {
        List<User> users = getUsersByUsername(userDto.getUsername());
        if (users.size()>1){
            throw new MyServiceException(Constants.CODE_600,"数据库异常");
        }else if(users.size()==1){
            if (users.get(0).getPassword().equals(userDto.getPassword())){
                BeanUtil.copyProperties(users.get(0),userDto);
                userDto.setToken(TokenUtils.getToken(""+users.get(0).getId(),users.get(0).getPassword()));

//                1.通过roleFlag获取role的id
                HashMap<String, Object> rolesMap = new HashMap<>();
                rolesMap.put("roleFlag",userDto.getRoleFlag());
                List<Role> roles = roleMapper.selectAllRoles(rolesMap);
                if (roles.size()!=1){
                    throw new MyServiceException(Constants.CODE_600,"该用户身份异常,数据库中查询不到该身份");
                }
//                2.通过role的id获取其对应的menuId
                HashMap<String, Object> roleMenusMap = new HashMap<>();
                roleMenusMap.put("roleId",roles.get(0).getId());
                List<RoleMenu> roleMenus = roleMenuMapper.selectAllRoleMenus(roleMenusMap);
//                3.通过menuId获取menu,将menu信息传至前端
                ArrayList<Menu> menus = new ArrayList<>();
                for (RoleMenu roleMenu : roleMenus) {
                    HashMap<String, Object> menusMap = new HashMap<>();
                    menusMap.put("id",roleMenu.getMenuId());
                    List<Menu> menusTempData = menuMapper.selectAllMenus(menusMap);
                    if(menusTempData.size()>1){
                        throw new MyServiceException(Constants.CODE_600,"数据库中数据异常,有数据库中不存在的menuId");
                    }
                    menus.add(menusTempData.get(0));
                }
                userDto.setMenus(menus);
                return Result.success(userDto);
            }
        }
        throw new MyServiceException(Constants.CODE_400,"账号密码错误");
    }

    @Override
    public Result updateUser(User user,String old_username) {
        List<User> users = getUsersByUsername(old_username);
        if (users.size()>1){
            throw new MyServiceException(Constants.CODE_600,"数据库异常");
        }else if(users.size()==1){
            user.setId(users.get(0).getId());
            if(userMapper.updateUser(user)>0){
                List<User> list = getUsersByUsername(user.getUsername());
                UserDto userDto = new UserDto();
                BeanUtil.copyProperties(list.get(0),userDto);
                return Result.success(userDto);
            }else{
                return Result.fail(Constants.CODE_600,"数据库数据更新失败");
            }

        }
        throw new MyServiceException(Constants.CODE_400,"账号密码错误");
    }

    @Override
    public Result register(UserDto userDto) {
        List<User> users = getUsersByUsername(userDto.getUsername());
        if (users.size()>1){
            throw new MyServiceException(Constants.CODE_600,"数据库异常");
        }else if(users.size()==1){
            throw new MyServiceException(Constants.CODE_500,"username已经存在");
        }
        User user = new User();
        BeanUtil.copyProperties(userDto,user);

        if(saveUser(user)>0){
            return Result.success();
        }else {
            return Result.fail(Constants.CODE_600,"保存用户失败");
        }
    }

    @Override
    public User selectUserById(int id) {
        return userMapper.selectUserById(id);
    }

    public List<User> getUsersByUsername(String username){
        Map<String, Object> map = new HashMap<>();
        map.put("username",username);
        List<User> users = userMapper.selectByLimit(map);
        return users;
    }
}
